from PIL import Image, ImageDraw, ImageFont
from bitarray import bitarray
import struct



def get_pix(image):
    pixel = image.load()
    width, height = image.size
    bitmap = bitarray()
    for h in range(height):
        for w in range(width):
            if pixel[w, h] > 0:
                bitmap.append(False)
            else:
                bitmap.append(True)
    return bitmap


def get_gb2312_pix(unicode_code, w, h, usr_font):
    image = Image.new("1", (w, h), (1))
    d_usr = ImageDraw.Draw(image)
    try:
        d_usr.text((0, 0), chr(unicode_code), (0), font=usr_font)
    except:
        d_usr.text((0, 0), u" ", (0), font=usr_font)
    return get_pix(image)


font_width = 16
font_height = 16
truetypefile = 'C:\Windows\Fonts\simsun.ttc'


usr_font = ImageFont.truetype(truetypefile, font_height)

fo = open('C:\\Users\\17591\\Desktop\\aa.txt','wb+')

#常用汉字在unicode的范围是0x4E00到0x9F5

#for unicode_index in range(0x4E00, 0x9FA5):
#        data = get_gb2312_pix(unicode_index, font_width, font_height, usr_font)
#        for x in range (len(data)>>3):
#            temp= data[8*x : 8*(x+1)]
#            s = 0
#            for y in range (8):
#                if temp[7-y] == False: #反白
#                    s =  s + (0x01<<y)
#            fo.write(struct.pack('B', s))


for unicode_index in range(0, 127):
        data = get_gb2312_pix(unicode_index, font_width, font_height, usr_font)
        for x in range (len(data)>>3):
            temp= data[8*x : 8*(x+1)]
            s = 0
            for y in range (8):
                if temp[7-y] == False: #反白
                    s =  s + (0x01<<y)
            fo.write(struct.pack('B', s))



fo.close()
